package gro.ecorrdata.edata.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.MyUtil;
import gro.ecorrdata.edata.controller.PerimissionController;
/**
 * AdminRoleController
 */
@RestController
@RequestMapping("/admin_role")
public class AdminRoleController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PerimissionController perimissionController;

    @RequestMapping("/list")
    public BaseResponse<Map<String, Object>> getEDataTableList() {
        String sqlTotal =  "select count(*) as total from admin_role where isdel=0 ";
        Map<String, Object> result =  jdbcTemplate.queryForMap(sqlTotal);

        String sql = "SELECT ar.id,ar.name, (SELECT group_concat(au.username) FROM admin_user as au WHERE au.role_id=ar.id) as usernames,  ar.permission, ar.status, ar.note FROM admin_role as ar where isdel=0 ";
        try {
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            result.put("list", list);
            return new BaseResponse<>(true, "查询成功", result);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            return new BaseResponse<>(true, "查询失败", null);
        }
    }

    @PostMapping("/getrole")
    public BaseResponse<Map<String, Object>> getRole(Integer id) {
        // PerimissionController pController = new PerimissionController();
        List<Map<String, Object>> pList = perimissionController.getListTree();
        String sql = "select id,name,permission,note from admin_role where id=?";
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);

            result.put("role", map);
            result.put("pList", pList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResponse<>(true, "查询成功", result);
    }

    @PostMapping("/update")
    public BaseResponse<Object> update(HttpServletRequest request) {
        boolean result = false;
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        if (name==null || name== "") {
            return new BaseResponse<>(false, "角色名不能为空", null);
        }
        Integer pid = (request.getParameter("pid")==null || request.getParameter("pid")=="") ? 0 : Integer.parseInt(request.getParameter("pid"));
        String[] arr = request.getParameterValues("check[]");
        String permission = StringUtils.join(arr, ",");
        // System.out.println(Arrays.toString(arr));
        String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
        Long ctime = (Long) (System.currentTimeMillis()/1000);
        if (id == null || id=="") {  // 添加
            
            String sql = "INSERT INTO admin_role(name, permission, create_time, note) VALUES(?,?,?,?)";
            
            int itemp = jdbcTemplate.update(sql,new Object[]{name, permission, ctime, note});

            if (itemp > 0) {
                result =true;
            }
        } else {   // 修改
            String sql = "UPDATE admin_role SET name=?, permission=?, note=?, modify_time=?  where `id`=? ";

            int itemp = jdbcTemplate.update(sql, new Object[]{name, permission, note, ctime, id});

            if (itemp > 0) {
                result =true;
            }   
        }

        if (result==true) {
            System.out.println("Ok!");
            return new BaseResponse<>(true, "操作成功!", null);
        } else {
            System.out.println("Error!");
            return new BaseResponse<>(false, "操作失败!", null);
        }
    }

    @PostMapping("/delete")
    public BaseResponse<Object> delete(Integer id) {
        boolean result = false;
        if (id == null) {
            return new BaseResponse<>(false, "找不到要删除的数据", null);
        }

        String sql = "SELECT count(*) as counts FROM admin_user WHERE isdel=0 and role_id=?";

        Map<String, Object> res = jdbcTemplate.queryForMap(sql, id);

        Long count = (Long) res.get("counts");
        // System.out.println(count);

        if (count!=0) {
            return new BaseResponse<>(false, "用户不为空不可删除", null);
        }

        String sql2 = "UPDATE admin_role SET `isdel`=1 where `id`=?";
        // System.out.println(sql);
        // System.out.println(id);
        try {
            jdbcTemplate.update(sql2, id);
            
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return new BaseResponse<>(result, "操作成功", null);
    }
}